package cn.tedu.csmall.order.webapi.service.impl;


import cn.tedu.csmall.cart.service.ICartService;
import cn.tedu.csmall.commons.exception.CoolSharkServiceException;
import cn.tedu.csmall.commons.pojo.order.dto.OrderAddDTO;
import cn.tedu.csmall.commons.pojo.order.model.OrderTb;
import cn.tedu.csmall.commons.pojo.stock.dto.StockReduceCountDTO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.commons.restful.ResponseCode;
import cn.tedu.csmall.order.service.IOrderService;
import cn.tedu.csmall.order.webapi.mapper.OrderMapper;
import cn.tedu.csmall.stock.service.IStockService;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

@Service
@Slf4j
@DubboService
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private OrderMapper orderMapper;

//    @Autowired
//    private RestTemplate restTemplate;
    //消费者
    @DubboReference
    IStockService stockService;

    @DubboReference
    ICartService cartService;

    @Override
    public void orderAdd(OrderAddDTO orderAddDTO) {
        // 1.减少订单商品的库存数(要调用stock模块的方法)
        // 1、stock 加注解  2、注入R   3、初始对象DTO 4、发起调用
        //模拟请求调用的形式---已经不用了
        StockReduceCountDTO stockReduceCountDTO = new StockReduceCountDTO();
        stockReduceCountDTO.setCommodityCode(orderAddDTO.getCommodityCode());
        stockReduceCountDTO.setReduceCount(orderAddDTO.getCount());
// http://stock/base/stock/reduce/count
//        restTemplate.postForObject("http://stock/base/stock/reduce/count"
//                ,stockReduceCountDTO,JsonResult.class);
        stockService.reduceCommodityCount(stockReduceCountDTO);
        System.out.println("调用stock服务");
        // 2.删除订单中勾选的购物车中的商品(要调用cart模块的方法)
        cartService.deleteUserCart(orderAddDTO.getUserId(),orderAddDTO.getCommodityCode());
        System.out.println("调用cart服务");

        // 3.新增订单
        OrderTb order=new OrderTb();
        BeanUtils.copyProperties(orderAddDTO,order);
        // 执行新增
        int row = orderMapper.insertOrder(order);
        if (row==0){
            throw new CoolSharkServiceException(
                    ResponseCode.BAD_REQUEST,
                    "新增订单失败"
            );
        }
        log.info("新增的订单信息:{}",order);
    }
}
